import OSS from 'ali-oss'
import { getAliOssSts } from '@/api/group/productOutbound/index'




// 推送文件
export const put = async (ObjName: string, fileUrl: string) => {
    try {
        let credentials: any = null;
        // 判断是否过期
        // 过期，重新获取
        if (Number(localStorage.getItem("expire")) - new Date().getTime() <= 60000) {
            const response = await getAliOssSts({});
            localStorage.setItem("expire", String(new Date(response.data.expire).getTime()))
            localStorage.setItem("credentials", JSON.stringify(response.data))
            credentials = JSON.parse(localStorage.getItem("credentials") || '')
        } else {
            credentials = JSON.parse(localStorage.getItem("credentials") || '')
        }

        let client = new OSS({
            region: 'oss-cn-beijing',    //创建的时候，bucket所在的区域，华北2->oss-cn-beijing ；其他的可以去百度
            bucket: "huimai-scm",
            accessKeyId: credentials.accessKeyId,// 阿里云控制台创建的AccessKey
            accessKeySecret: credentials.accessKeySecret, //阿里云控制台创建的AccessSecret
            ststoken: credentials.securityToken,
            timeout: 300000
        })
        let result = await client.put(`uploads/${ObjName}`, fileUrl, {
            headers: {
                'x-oss-security-token': credentials.securityToken, // 设置安全令牌
            },
        })
        // ObjName为文件名字,可以只写名字，就直接储存在 bucket 的根路径，如需放在文件夹下面直接在文件名前面加上文件夹名称    
        return result
    } catch (e) {
        console.log(e)
    }
}

// uuid
export const getFileNameUUID = () => {
    function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return `${+new Date()}_${rx()}${rx()}`
}

